package com.erp.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.order.domain.bo.ErpSellerOrderLogBo;
import com.erp.order.domain.vo.ErpSellerOrderLogVo;
import com.erp.order.mapper.ErpSellerOrderExtendMapper;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.web.oldDomain.BaseEntity;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderExtend;
import com.ruoyi.order.api.domain.ErpSellerOrderLog;
import com.ruoyi.common.core.enums.OrderLogType;
import com.erp.order.mapper.ErpSellerOrderLogMapper;
import com.erp.order.mapper.ErpSellerOrderMapper;
import com.erp.order.service.IErpSellerOrderLogService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 订单日志Service业务层处理
 *
 * @author erp
 * @date 2023-04-12
 */
@RequiredArgsConstructor
@Service
public class ErpSellerOrderLogServiceImpl implements IErpSellerOrderLogService {

    @Resource
    private RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    private RemoteUserService remoteUserService;

    private final ErpSellerOrderLogMapper baseMapper;
    private final ErpSellerOrderMapper erpSellerOrderMapper;
    private final ErpSellerOrderExtendMapper erpSellerOrderExtendMapper;
//    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
//    private final SysUserMapper sysUserMapper;
//
//    /**
//     * 查询订单日志
//     */
//    @Override
//    public ErpSellerOrderLogVo queryById(Long id) {
//        return baseMapper.selectVoById(id);
//    }
//
//    /**
//     * 查询订单日志列表
//     */
//    @Override
//    public TableDataInfo<ErpSellerOrderLogVo> queryPageList(ErpSellerOrderLogBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<ErpSellerOrderLog> lqw = buildQueryWrapper(bo);
//        Page<ErpSellerOrderLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
//    }
//
//    /**
//     * 查询订单日志列表
//     */
//    @Override
//    public List<ErpSellerOrderLogVo> queryList(ErpSellerOrderLogBo bo) {
//        LambdaQueryWrapper<ErpSellerOrderLog> lqw = buildQueryWrapper(bo);
//        return baseMapper.selectVoList(lqw);
//    }
//
//    private LambdaQueryWrapper<ErpSellerOrderLog> buildQueryWrapper(ErpSellerOrderLogBo bo) {
//        Map<String, Object> params = bo.getParams();
//        LambdaQueryWrapper<ErpSellerOrderLog> lqw = Wrappers.lambdaQuery();
//        lqw.like(StringUtils.isNotBlank(bo.getStoreName()), ErpSellerOrderLog::getStoreName, bo.getStoreName());
//        lqw.eq(bo.getErpAccount() != null, ErpSellerOrderLog::getErpAccount, bo.getErpAccount());
//        lqw.eq(bo.getOrderId() != null, ErpSellerOrderLog::getOrderId, bo.getOrderId());
//        lqw.eq(StringUtils.isNotBlank(bo.getChildOrderId()), ErpSellerOrderLog::getChildOrderId, bo.getChildOrderId());
//        lqw.eq(StringUtils.isNotBlank(bo.getStatusIntro()), ErpSellerOrderLog::getStatusIntro, bo.getStatusIntro());
//        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerOrderLog::getRevision, bo.getRevision());
//        return lqw;
//    }
//
//    /**
//     * 新增订单日志
//     */
//    @Override
//    public Boolean insertByBo(ErpSellerOrderLogBo bo) {
//        ErpSellerOrderLog add = BeanUtil.toBean(bo, ErpSellerOrderLog.class);
//        validEntityBeforeSave(add);
//        boolean flag = baseMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
//        return flag;
//    }

    /**
     * 修改订单日志
     */
    @Override
    public Boolean updateByBo(ErpSellerOrderLogBo bo) {
        ErpSellerOrderLog update = BeanUtil.toBean(bo, ErpSellerOrderLog.class);
        return baseMapper.updateById(update) > 0;
    }
//
//    /**
//     * 保存前的数据校验
//     */
//    private void validEntityBeforeSave(ErpSellerOrderLog entity) {
//        //TODO 做一些数据校验,如唯一约束
//    }
//
//    /**
//     * 批量删除订单日志
//     */
//    @Override
//    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if (isValid) {
//            //TODO 做一些业务上的校验,判断是否需要校验
//        }
//        return baseMapper.deleteBatchIds(ids) > 0;
//    }

    @Override
    public List<ErpSellerOrderLogVo> selectOrderLogByOrderId(Long orderId) {

        return baseMapper.selectOrderLogByOrderId(orderId);
    }

    @Override
    public ErpSellerOrderLog getStatusIntro(Long orderId) {
        ErpSellerOrderLog logList = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerOrderLog>().eq(ErpSellerOrderLog::getOrderId, orderId)
                        .orderByDesc(BaseEntity::getCreateTime)
                        .last("limit 1")
        );
        return logList;
    }
//
    @Override
    public ErpSellerOrderLog queryByStatusIntroAndOrderId(String Str, Long orderId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrderLog>()
                .eq(ErpSellerOrderLog::getOrderId, orderId)
                .eq(ErpSellerOrderLog::getStatusIntro, Str)
                .last("limit 1")
        );
    }

    /**
     * 新版创建订单日志 在订单修改之前
     * @param orderId
     * @param orderLogType
     * @param remark
     * @return
     */
    @Override
    public R<Object> createOrderLog(
            Long orderId,
            String childOrderId,
            OrderLogType orderLogType,
            String remark,
            //下一个流程的流程代码
            String orderProcessFlagInfo,
            //下一个流程的状态
            String erpStatus
    ) {

        ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
        if (order == null) {
            return R.fail("订单不存在");
        }

        //只在拉取订单查看是否出库时确定
//        ErpSellerOrderLog log = baseMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderLog>()
//                        .eq(ErpSellerOrderLog::getOrderId, orderId)
//                        .eq(ErpSellerOrderLog::getType, orderLogType.getCode())
//                        .eq(ErpSellerOrderLog::getCurrentStatus, erpStatus)
//        );
        ErpSellerOrderLog log = new ErpSellerOrderLog();

        log.setOrderId(orderId);
        log.setChildOrderId(childOrderId);

        // 获取店铺授权信息
        R<Object> storeEmpowerObject = remoteSellerStoreService.getStoreEmpowerListByCnCode(order.getSellerLoginId());
        if(storeEmpowerObject.getCode() != 200){
            R.fail("获取店铺授权信息错误，日志添加失败");
        }
        String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
        ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(storeEmpowerString, ErpSellerStoreEmpower.class);

        // 获取ERP用户信息
//        R<Object> userObject = remoteUserService.selectUserById(storeEmpower.getUserId());
//        if(userObject.getCode() != 200){
//            R.fail("获取ERP用户信息错误，日志添加失败");
//        }
//        String userString = JSONObject.toJSONString(userObject.getData());
//        SysUser user = JSONObject.parseObject(userString, SysUser.class);

        log.setErpAccount(SecurityUtils.getUsername());
        log.setStoreName(storeEmpower.getStoreUserName());
        log.setStatusIntro(orderLogType.getInfo());
        log.setRemark(remark);
        log.setType(orderLogType.getCode());
        //订单在创建日志前的流程代码

        log.setPreviousOrderProcess(order.getOrderProcessFlag());
        log.setCurrentOrderProcess(orderProcessFlagInfo);

        log.setPreviousStatus(order.getErpInnerOrderStatus());
        log.setCurrentStatus(erpStatus);

        baseMapper.insert(log);

        return R.ok("日志添加成功");
    }
//
//    @Override
//    public void updateOrderLog() {
//        LambdaQueryWrapper<ErpSellerOrderLog> queryWrapper = new LambdaQueryWrapper<ErpSellerOrderLog>().orderByAsc(BaseEntity::getCreateTime);
//        List<ErpSellerOrderLog> orderLogList = baseMapper.selectList(queryWrapper);
//        for (ErpSellerOrderLog orderLog : orderLogList) {
//            if (StringUtils.isEmpty(orderLog.getCurrentStatus())) {
//                continue;
//            }
//            String statusIntro = orderLog.getStatusIntro();
//            if (StringUtils.isEmpty(statusIntro)) {
//                continue;
//            }
//            if ("订单提交待发货审核".equals(statusIntro)) {
//                orderLog.setPreviousStatus("101");
//                orderLog.setCurrentStatus("103");
//                orderLog.setOrderProcessFlag("cainiao");
//            }else if ("采购审核不通过".equals(statusIntro)) {
//                orderLog.setPreviousStatus("103");
//                orderLog.setCurrentStatus("101");
//                orderLog.setOrderProcessFlag("begin");
//            }else if (statusIntro.contains("已同步国内运单")) {
//                orderLog.setPreviousStatus("103");
//                orderLog.setCurrentStatus("105");
//                orderLog.setOrderProcessFlag("cainiao");
//            }else if ("上传购买凭证".equals(statusIntro)) {
//                orderLog.setPreviousStatus("103");
//                orderLog.setCurrentStatus("105");
//                orderLog.setOrderProcessFlag("cainiao");
//            }else if ("订单已发货".equals(statusIntro)) {
//                orderLog.setPreviousStatus("105");
//                orderLog.setCurrentStatus("106");
//                orderLog.setOrderProcessFlag("cainiao");
//            }else if ("订单已出库".equals(statusIntro)) {
//                orderLog.setPreviousStatus("106");
//                orderLog.setCurrentStatus("107");
//                orderLog.setOrderProcessFlag("cainiao");
//            }else if ("订单作废".equals(statusIntro)) {
//                orderLog.setCurrentStatus("901");
//                orderLog.setPreviousStatus("101");
//                orderLog.setOrderProcessFlag("Invalid");
//            }
//            baseMapper.updateById(orderLog);
//        }
//    }


    /**
     * 获取订单驳回和截单记录
     * @param pageQuery
     * @param log
     * @return
     */
    @Override
    public TableDataInfo<ErpSellerOrderLogVo> getRejectAndCutOffRecord(PageQuery pageQuery, ErpSellerOrderLogBo log) {
        LambdaQueryWrapper<ErpSellerOrderLog> lqw = buildRecordQueryWrapper(log);
        Page<ErpSellerOrderLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
//
//    @Override
//    public R<Object> checkOrderLog(Long orderId, OrderLogType orderLogType, String orderProcessFlagInfo) {
//        ErpSellerOrderLog log = baseMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderLog>()
//                        .eq(ErpSellerOrderLog::getOrderId,orderId)
//                        .eq(ErpSellerOrderLog::getCurrentOrderProcess,orderProcessFlagInfo)
//                        .eq(ErpSellerOrderLog::getType,orderLogType.getCode())
//                        .last("limit 1")
//
//        );
//        if (ObjectUtils.isNotEmpty(log)){
//            //已经有存在的数据了
//            return R.ok();
//        }else {
//            return R.fail();
//        }
//    }

    /**
     * 设置订单备注
     * @param orderId
     * @param memo
     * @return
     */
    @Override
    public R<Object> setOrderMemo(Long orderId, String memo) {
        ErpSellerOrderExtend extend = erpSellerOrderExtendMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId,orderId)
        );
        if (ObjectUtils.isEmpty(extend)){
            extend = new ErpSellerOrderExtend();
            extend.setOrderId(orderId);
            extend.setMemo(memo);
        }else {
            extend.setMemo(memo);
        }
        erpSellerOrderExtendMapper.insertOrUpdate(extend);
        return R.ok("设置成功");
    }

    private LambdaQueryWrapper<ErpSellerOrderLog> buildRecordQueryWrapper(ErpSellerOrderLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerOrderLog> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getStoreName()), ErpSellerOrderLog::getStoreName, bo.getStoreName());
        lqw.eq(bo.getOrderId() != null, ErpSellerOrderLog::getOrderId, bo.getOrderId());
        if (bo.getType() != null && !bo.getType().equals("")){
            lqw.eq(bo.getType() != null, ErpSellerOrderLog::getType, bo.getType());
        }else {
            lqw.in(ErpSellerOrderLog::getType,501,502,503);
        }
        lqw.orderByDesc(ErpSellerOrderLog::getCreateTime);
        return lqw;
    }
}
